<?php
namespace DaChongQing\Controller;
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2015/4/16
 * Time: 9:18
 * 客服接口开发
 */


/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2015/4/17
 * Time: 15:45
 */

//$kefu = new kefuPush('wxdada6ee2d8','asd','o9pT9t9S_wMcQAQIOtJjopc0584c');
//$kefu -> pay();
//$kefu -> PushText('你好收到了请回话');
//$kefu -> uploadMedia('image','/usr/share/nginx/html/weixin/WeiXin/TPL/Images/abcd.jpg');
//$kefu -> PushNews('asdas','asdasdasdasdasd','http://www.baidu.com','http://www.weirongm.com/weixin/WeiXin/TPL/Images/abcd.jpg');die;
//$kefu -> PushImg('1eGxFHUzoQEr-H1o7h1rTsFHBuspUuHma0d1v1QV7aZagLgShdupsDKLKSaCU5zr');

 $options = array(
            'appid'=>C("appid"), //填写你设定的key
            'appsecret'=>C("appsecret"),
        );
        $wechat = new Wechat($options);
        dump($wechat->checkAuth());
        die;


Class kefuPush{
    /**
     * @$appid
     */
    protected $appid;
    /**
     * @$appsecrect
     */
    protected $appsecret;
    /**
     * @var $open_id:用户的唯一标识
     */
    protected $open_id;

    public function __construct($appid = '' , $appsecret = '' , $open_id = ''){
        if( $appid == '' || $appsecret == '' || $open_id == '' ) return false;
        $this->appid = $appid;
        $this->appsecret = $appsecret;
        $this->open_id = $open_id;
//        dump(AccessToken());
    }

    /**
     * @return mixed
     * 获取access_token
     */
    public function getAccessToken(){
        return AccessToken();
//        $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$this->appid.'&secret='.$this->appsecret.'';
//        $jsonReturn = file_get_contents($url);
//        $jsonReturn = json_decode($jsonReturn);
//        return $jsonReturn->access_token;
    }

    /**
     * @param $type媒体文件类型，分别为voice,image,video,thumb
     * @param $mediaUrl所要上传的媒体文件路径
     */
    public function uploadMedia($type,$mediaUrl){
        $uploadUrl = 'https://api.weixin.qq.com/cgi-bin/media/upload?access_token='.self::getAccessToken().'&type='.$type.'';
        $data = array('media' => '@'.realpath($mediaUrl));
        $ch = curl_init();
        curl_setopt($ch,CURLOPT_URL,$uploadUrl);
        curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
        curl_setopt($ch,CURLOPT_POST,1);
        curl_setopt($ch,CURLOPT_POSTFIELDS,$data);
        $info = curl_exec($ch);
        if(curl_errno($ch)) echo "Error:".curl_error($ch);
        print_r($mediaUrl);
        curl_close($ch);
        print_r($info);
    }

    /**
     * @param $postMsg json数据
     * @return mixed
     */
    public function postMsg($postMsg){
        $access_token = self::getAccessToken();
        $get_msg_url = 'https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token='.$access_token;
        $ch = curl_init();
        curl_setopt($ch,CURLOPT_URL,$get_msg_url);
        curl_setopt($ch,CURLOPT_CUSTOMREQUEST,"POST");
        curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,FALSE);
        curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,FALSE);
        curl_setopt($ch,CURLOPT_USERAGENT,'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
        curl_setopt($ch,CURLOPT_FOLLOWLOCATION,1);
        curl_setopt($ch,CURLOPT_AUTOREFERER,1);
        curl_setopt($ch,CURLOPT_POSTFIELDS,$postMsg);
        curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
        $info = curl_exec($ch);
        if(curl_errno($ch)) echo "Error".curl_error($ch);
        curl_close($ch);
        $arrInfo = json_decode($info);
        return $arrInfo;
    }

    /**
     * 纯文本消息的推送
     * @param $content推送的消息内容
     */
    public function PushText($content){
        $content = urlencode(trim($content));
        $data = array(
            'touser' => $this->open_id,
            'msgtype' => 'text',
            'text' => array(
                'content' => $content
            )
        );
        $post_json_data = urldecode(json_encode($data));
        $result = self::postMsg($post_json_data);
        return $result->errmsg;
    }

    /**
     * @param $media_id图片media_id
     */
    public function PushImg($media_id){
        $media_id = urlencode(trim($media_id));
        $data = array(
            'touser' => $this->open_id,
            'msgtype' => 'image',
            'image' => array(
                'media_id' => $media_id
            )
        );
        $post_json_data = urldecode(json_encode($data));
        $result = self::postMsg($post_json_data);
        print_r($result);
        return $result->errmsg;
    }

    /**
     * @param $media_id语音media_id
     */
    public function PushVoice($media_id){
        $media_id = urlencode(trim($media_id));
        $data = array(
            'touser' => $this->open_id,
            'msgtype' => 'voice',
            'vioce' => array(
                'media_id' => $media_id
            )
        );
        $post_json_data = urldecode(json_encode($data));
        $result = self::postMsg($post_json_data);
        print_r($result);
        return $result->errmsg;
    }

    /**
     * @param $media_id视频media_id
     * @param $title标题
     * @param $description简介
     */
    public function PushVideo($media_id,$title,$description){
        $media_id = urlencode(trim($media_id));
        $data = array(
            'touser' => $this->open_id,
            'msgtype' => 'video',
            'video' => array(
                'media_id' => $media_id,
                'title' => $title,
                'description' => $description
            )
        );
        $post_json_data = urldecode(json_encode($data));
        $result = self::postMsg($post_json_data);
        print_r($result);
        return $result->errmsg;
    }

    /**
     * $title音乐标题
     * $description音乐介绍
     * $musicurl音乐链接
     * $hqmusicurl高品质音乐链接
     * $thumb_media_id缩略图ID
     */
    public function PushMusic($title,$description,$musicurl,$hqmusicurl,$thumb_media_id){
        $data = array(
            'touser' => $this->open_id,
            'msgtype' => 'music',
            'music' => array(
                'title' => $title,
                'description' => $description,
                'musicurl' => $musicurl,
                'hqmusicurl' => $hqmusicurl,
                'thumb_media_id' => $thumb_media_id
            )
        );
        $post_json_data = urldecode(json_encode($data));
        $result = self::postMsg($post_json_data);
        print_r($result);
        return $result->errmsg;
    }

    /**
     * @param $media_id语音media_id
     */
    public function PushNews($title,$description,$url,$picUrl){
        $data = array(
            "touser" => $this->open_id,
            "msgtype" => "news",
            "news" => array(
                "articles" => array(
                    array(
                        "title" => $title,
                        "description" => $description,
                        "url" => $url,
                        "picurl" => $picUrl
                    )
                )
            )
        );
        $post_json_data = urldecode(json_encode($data));
        $result = self::postMsg($post_json_data);
        print_r($result);
        return $result->errmsg;
    }
     public function pay(){
         echo "hello world";
     }
}







$pay = new WxApi();
$md5sign = $pay->SetSign();
$parameters = array(
    'nonce_str' => '123123131231321',
    'sign' => $md5sign,
    'mch_billno' => $pay->wxMchBillno('1252370801'),
    'mch_id' => '1252370801',
    'wxappid' => 'wx22c589512a2d5f61',
    'nick_name' => '我爱大重庆',
    'send_name' => '我爱大重庆',
    're_openid' => 'o9pT9t7fkvp8vw7XaeGDkZJgm7BM',
    'total_amount' => '200',
    'min_value' => '200',
    'max_value' => '200',
    'total_num' => '1',
    'wishing' => '恭喜发财！',
    'client_ip' => '121.40.30.107',
    'act_name' => '恭喜发财',
    'remark' => '恭喜发财'
);

$url = 'https://api.mch.weixin.qq.com/mmpaymkttransfers/sendredpack';
$info = $pay->wxHttpsRequestPem($url,$pay->wxArrayToXml($parameters));

dump($info);
  class WxApi {
      public $parameters = array();
      const mchid     = "1252370801"; //商户号
      const privatekey  = "U2ZqlI1AvF1Ac3nrm2GqTqgyOmlICxHP"; //私钥
      public function __construct(){
        $this->parameters = array(
            'nonce_str' => '123123131231321',
            'sign' => self::SetSign($this->parameters),
            'mch_billno' => self::wxMchBillno('1252370801'),
            'mch_id' => '1252370801',
            'wxappid' => 'wx22c589512a2d5f61',
            'nick_name' => '我爱大重庆',
            'send_name' => '我爱大重庆',
            're_openid' => 'o9pT9t7fkvp8vw7XaeGDkZJgm7BM',
            'total_amount' => '200',
            'min_value' => '200',
            'max_value' => '200',
            'total_num' => '1',
            'wishing' => '恭喜发财！',
            'client_ip' => '121.40.30.107',
            'act_name' => '恭喜发财',
            'remark' => '恭喜发财'
        );
      }

      /****************************************************
       * 微信提交API方法，返回微信指定JSON
       ****************************************************/

      public function wxHttpsRequest($url,$data = null){
          $curl = curl_init();
          curl_setopt($curl, CURLOPT_URL, $url);
          curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
          curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
          if (!empty($data)){
              curl_setopt($curl, CURLOPT_POST, 1);
              curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
          }
          curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
          $output = curl_exec($curl);
          curl_close($curl);
          return $output;
      }

      /****************************************************
       * 微信带证书提交数据 - 微信红包使用
       ****************************************************/

      public function wxHttpsRequestPem($url, $vars, $second=30,$aHeader=array()){
          $ch = curl_init();
          //超时时间
          curl_setopt($ch,CURLOPT_TIMEOUT,$second);
          curl_setopt($ch,CURLOPT_RETURNTRANSFER, 1);
          //这里设置代理，如果有的话
          //curl_setopt($ch,CURLOPT_PROXY, '10.206.30.98');
          //curl_setopt($ch,CURLOPT_PROXYPORT, 8080);
          curl_setopt($ch,CURLOPT_URL,$url);
          curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false);
          curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,false);

          //以下两种方式需选择一种

          //第一种方法，cert 与 key 分别属于两个.pem文件
          //默认格式为PEM，可以注释
          curl_setopt($ch,CURLOPT_SSLCERTTYPE,'PEM');
          curl_setopt($ch,CURLOPT_SSLCERT,getcwd().'/apiclient_cert.pem');
          //默认格式为PEM，可以注释
          curl_setopt($ch,CURLOPT_SSLKEYTYPE,'PEM');
          curl_setopt($ch,CURLOPT_SSLKEY,getcwd().'/apiclient_key.pem');

          curl_setopt($ch,CURLOPT_CAINFO,'PEM');
          curl_setopt($ch,CURLOPT_CAINFO,getcwd().'/rootca.pem');

          if( count($aHeader) >= 1 ){
              curl_setopt($ch, CURLOPT_HTTPHEADER, $aHeader);
          }

          curl_setopt($ch,CURLOPT_POST, 1);
          curl_setopt($ch,CURLOPT_POSTFIELDS,$vars);
          $data = curl_exec($ch);
          if($data){
              curl_close($ch);
              return $data;
          }
          else {
              $error = curl_errno($ch);
              echo "call faild, errorCode:$error\n";
              curl_close($ch);
              return false;
          }
      }

      /****************************************************
       * 微信获取AccessToken 返回指定微信公众号的at信息
       ****************************************************/

      public function wxAccessToken(){
          return AccessToken();
      }

      /*****************************************************
       *   生成随机字符串 - 最长为32位字符串
       *****************************************************/
      public function wxNonceStr($length = 16, $type = FALSE) {
          $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
          $str = "";
          for ($i = 0; $i < $length; $i++) {
              $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
          }
          if($type == TRUE){
              return strtoupper(md5(time() . $str));
          }
          else {
              return $str;
          }
      }

      /*******************************************************
       *   微信商户订单号 - 最长28位字符串
       *******************************************************/

      public function wxMchBillno($mchid = NULL) {
          if(is_null($mchid)){
              if(self::mchid == "" || is_null(self::mchid)){
                  $mchid = time();
              }
              else{
                  $mchid = self::mchid;
              }
          }
          else{
              $mchid = substr(addslashes($mchid),0,10);
          }
          return $mchid.date("Ymd",time()).time();
      }

      /*******************************************************
       *   微信格式化数组变成参数格式 - 支持url加密
       *******************************************************/

      public function wxSetParam($parameters){
          if(is_array($parameters) && !empty($parameters)){
              $this->parameters = $parameters;
              return $this->parameters;
          }
          else{
              return array();
          }
      }

      /*******************************************************
       *   微信格式化数组变成参数格式 - 支持url加密
       *******************************************************/

      public function wxFormatArray($parameters = NULL, $urlencode = FALSE){
          if(is_null($parameters)){
              $parameters = $this->parameters;
          }
          $restr = "";//初始化空
          ksort($parameters);//排序参数
          foreach ($parameters as $k => $v){//循环定制参数
              if (null != $v && "null" != $v && "sign" != $k) {
                  if($urlencode){//如果参数需要增加URL加密就增加，不需要则不需要
                      $v = urlencode($v);
                  }
                  $restr .= $k . "=" . $v . "&";//返回完整字符串
              }
          }
          if (strlen($restr) > 0) {//如果存在数据则将最后“&”删除
              $restr = substr($restr, 0, strlen($restr)-1);
          }
          return $restr;//返回字符串
      }

      /*******************************************************
       *   微信MD5签名生成器 - 需要将参数数组转化成为字符串[wxFormatArray方法]
       *******************************************************/

      public function SetSign()
      {
          $sign = $this->MakeSign();
          $this->parameters['sign'] = $sign;
          return $sign;
      }

      public function MakeSign()
      {
          //签名步骤一：按字典序排序参数
          ksort($this->parameters);
          $string = $this->ToUrlParams();
          //签名步骤二：在string后加入KEY
          $string = $string . "&key=".self::privatekey;
//          dump($this->parameters);
          //签名步骤三：MD5加密
          $string = md5($string);
          //签名步骤四：所有字符转为大写
          $result = strtoupper($string);
          return $result;
      }

      public function ToUrlParams()
      {
          $buff = "";
          foreach ($this->parameters as $k => $v)
          {
              if($k != "sign" && $v != "" && !is_array($v)){
                  $buff .= $k . "=" . $v . "&";
              }
          }

          $buff = trim($buff, "&");
          return $buff;
      }


      /*******************************************************
       *   将数组解析XML - 微信红包接口
       *******************************************************/

      public function wxArrayToXml($parameters = NULL){
          if(is_null($parameters)){
              $parameters = $this->parameters;
          }

          if(!is_array($parameters) || empty($parameters)){
              die("参数不为数组无法解析");
          }

          $xml = "<xml>";
          foreach ($parameters as $key=>$val)
          {
              if (is_numeric($val))
              {
                  $xml.="<".$key.">".$val."</".$key.">";
              }
              else
                  $xml.="<".$key."><![CDATA[".$val."]]></".$key.">";
          }
          $xml.="</xml>";
          return $xml;
      }

  }














/**
 * 微信红包的类
 * @Author snmoney#gmail.com
 * @blog http://snmoney.blog.163.com
 * @copyright 2015
 * @version 1.0
 *
 * 本类可任意授权使用，务必保留作者信息以便侦错改进；
 * 对因修改源码产生直接或间接经济损失，作者不承担任何责任。
 *
 * *微信红包还有部分可选的参数，如分享预设值等将在后续版本补充上相关功能。
 */

//$hb = new WXHongBao();
//$hb->newhb('o9pT9t9S_wMcQAQIOtJjopc0584c',1000); //新建一个10元的红包，第二参数单位是 分，注意取值范围 1-200元
//
////以下若干项可选操作，不指定则使用class脚本顶部的预设值
//
//  $hb->setNickName("土豪有限公司");
//
//  $hb->setSendName("王富贵");
//
//  $hb->setWishing("恭喜发财");
//
//  $hb->setActName("发钱活动");
//
//  $hb->setRemark("有钱!任性!");
//
////发送红包
//
//if(!$hb->send()){ //发送错误
//
////    dump($hb->err());
//    var_dump($hb->err());
//}else{
//
//    echo "红包发送成功";
//
//}


CLASS WXHongBao {

    private $mch_id = "1200000001";//商户ID写死
    private $wxappid = "wx22c589512a2d5f61";//微信公众号，写死
    private $client_ip = "121.40.30.107"; //调用红包接口的主机的IP,服务端IP,写死，即脚本文件所在的IP
    private $apikey = "U2ZqlI1AvF1Ac3nrm2GqTqgyOmlICxHP";//写死，pay的秘钥值
    private $total_num = 1;//发放人数。固定值1，不可修改

    private $nick_name = "我爱大重庆"; //红包商户名称
    private $send_name = "我爱大重庆";//红包派发者名称
    private $wishing = "你好啊"; //
    private $act_name = "你好好"; //活动名称
    private $remark = "你好啊";
    private $nonce_str = "";
    private $mch_billno = "";
    private $re_openid = "";//接收方的openID
    private $total_amount = 100 ;//红包金额，单位 分
    private $min_value = 100;//最小金额
    private $max_value = 100; //根据接口要求，上述3值必须一致
    private $sign = ""; //签名在send时生成

    //证书，在构造函数中定义，注意！
    private $apiclient_cert; //= getcwd()."/apiclient_cert.pem";
    private $apiclient_key;// = getcwd()."/apiclient_key.pem";

    private $wxhb_inited; //初始值默认为false,判定红包是否已newhb()方式初始化

    private $error = "ok"; //init



    /**
     * WXHongBao::__construct()
     * 步骤
     * new(openid,amount)
     * setnickname
     * setsend_name
     * setwishing
     * setact_name
     * setremark
     * send()
     * @return void
     */
    function __construct(){
        //好像没有什么需要构造函数做的
        $this->wxhb_inited = false;
        $this->apiclient_cert = "
-----BEGIN CERTIFICATE-----
MIIEaDCCA9GgAwIBAgIDA8J8MA0GCSqGSIb3DQEBBQUAMIGKMQswCQYDVQQGEwJD
TjESMBAGA1UECBMJR3Vhbmdkb25nMREwDwYDVQQHEwhTaGVuemhlbjEQMA4GA1UE
ChMHVGVuY2VudDEMMAoGA1UECxMDV1hHMRMwEQYDVQQDEwpNbXBheW1jaENBMR8w
HQYJKoZIhvcNAQkBFhBtbXBheW1jaEB0ZW5jZW50MB4XDTE1MDcwODA1MTUwMloX
DTI1MDcwNTA1MTUwMlowgZgxCzAJBgNVBAYTAkNOMRIwEAYDVQQIEwlHdWFuZ2Rv
bmcxETAPBgNVBAcTCFNoZW56aGVuMRAwDgYDVQQKEwdUZW5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DPl+qgbiJCdR4rJqIWZmvk0T79LU9lQnK3
1pnPpK3Tpbw1A64rdcShC+Q0S3aswhbxd6kZjtt31Yb+KPEcapVQGLwSGIQ1wuWH
HFmLJt53aSLzvJgvEOSL1vwBJWkTeAAHeFyvmdn2tbgkHXwI1LvlfDN7zGeL5cPq
buHP2X9ZQwKBgCLyNyWVkyCkvFCszn0E/tWj2MU3PZl4IzLhcOIUjVjBo8me8FIY
Xq021RmiqwiGyibDAAecF8XK+S+X1QrgajIowNgQw6DeRCGhNkmreVypiRSxZNWW
HhC4Yy2d/4C0bDliy/8p+eT4hLECqLHQmLHYIQkbwTveq5IHIbrRkc67AoGBALw2
1XBNSlyMySSAa3b5t5sHKB/to82AGHibZmr/uOZqnqBGTPR0WylUmbvcK6Xod1rI
jhVxE4SroS/wuOJ1tBihxGp3te70XJxKVNk4DX2gYiMwe544p64t5d+4JnOTWhtr
wkUnrZnkGicMYHe1QQKIwDjfE4agdCeqDqwfWzn3AoGBAOIUhFskxwvP9qADcZuv
GCNIG1LyB+Zvkg4cB5GjfcwAB7AK8WMaClrrohJm0uy1vuNyVde5UJWkTK66MQl0
/WyZv7ySmwcTdjKnAncb+qrK+VmJeGPb/2kMbOVR9Gs1OO1mqYpggMyoK/OMNJ/Y
GvwP8FsA5xRkIukT+MV47UOC
-----END PRIVATE KEY-----
";
    }

    public function err(){
        return $this->error;
    }
    /**
     * WXHongBao::newhb()
     * 构造新红包
     * @param mixed $toOpenId
     * @param mixed $amount 金额分
     * @return void
     */
    public function newhb($toOpenId,$amount){
        if(!is_numeric($amount)){
            $this->error = "金额参数错误";
            return;
        }elseif($amount<100){
            $this->error = "金额太小";
            return;
        }elseif($amount>20000){
            $this->error = "金额太大";
            return;
        }

        $this->gen_nonce_str();//构造随机字串
        $this->gen_mch_billno();//构造订单号
        $this->setOpenId($toOpenId);
        $this->setAmount($amount);
        $this->wxhb_inited = true; //标记微信红包已经初始化完毕可以发送
    }

    /**
     * WXHongBao::send()
     * 发出红包
     * 构造签名
     * @return boolean $success
     */
    public function send(){
        if(!$this->wxhb_inited){
            $this->error .= "(红包未准备好)";
            return false; //未初始化完成
        }
        $this->gen_Sign(); //生成签名

        //构造提交的数据
        $xml = $this->genXMLParam();

        //提交xml,curl
        $url = "https://api.mch.weixin.qq.com/mmpaymkttransfers/sendredpack";
        $ch = curl_init();
        curl_setopt($ch,CURLOPT_TIMEOUT,10);
        curl_setopt($ch,CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch,CURLOPT_URL,$url);
        curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false);
        curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,false);

        curl_setopt($ch,CURLOPT_SSLCERTTYPE,'PEM');
        curl_setopt($ch,CURLOPT_SSLCERT,$this->apiclient_cert);
        curl_setopt($ch,CURLOPT_SSLKEYTYPE,'PEM');
        curl_setopt($ch,CURLOPT_SSLKEY,$this->apiclient_key);

        /*
    	if( count($aHeader) >= 1 ){
    		curl_setopt($ch, CURLOPT_HTTPHEADER, $aHeader);
    	}
        */
        curl_setopt($ch,CURLOPT_POST, 1);
        curl_setopt($ch,CURLOPT_POSTFIELDS,$xml);
        $data = curl_exec($ch);
        if($data){
            curl_close($ch);
            $rsxml = simplexml_load_string($data);
            if($rsxml->return_code == 'SUCCESS' ){
                return true;
            }else{
                $this->error = $rsxml->return_msg;
                return false;
            }

        }else{
            $this->error = curl_errno($ch);

            curl_close($ch);
            return false;
        }

    }

    public function setNickName($nick){
        $this->nick_name = $nick;
    }

    public function setSendName($name){
        $this->send_name = $name;
    }

    public function setWishing($wishing){
        $this->wishing = $wishing;
    }

    /**
     * WXHongBao::setActName()
     * 活动名称
     * @param mixed $act
     * @return void
     */
    public function setActName($act){
        $this->act_name = $act;
    }

    public function setRemark($remark){
        $this->remark = $remark;
    }

    public function setOpenId($openid){
        $this->re_openid = $openid;
    }

    /**
     * WXHongBao::setAmount()
     * 设置红包金额
     * 文档有两处冲突描述
     * 一处指金额 >=1 (分钱)
     * 另一处指金额 >=100 < 20000 [1-200元]
     * 有待测试验证！
     * @param mixed $price 单位 分
     * @return void
     */
    public function setAmount($price){
        $this->total_amount = $price;
        $this->min_value = $price;
        $this->max_value = $price;
    }

    private function gen_nonce_str(){
        $this->nonce_str = strtoupper(md5(mt_rand().time())); //确保不重复而已
    }

    private function gen_Sign(){
        unset($param);
        //其实应该用key重排一次 right?
        $param["act_name"]=$this->act_name;
        $param["client_ip"]=$this->client_ip;
        $param["max_value"]=$this->max_value;
        $param["mch_billno"] = $this->mch_billno;
        $param["mch_id"]=$this->mch_id;
        $param["min_value"]=$this->min_value;
        $param["nick_name"]=$this->nick_name;
        $param["nonce_str"]=$this->nonce_str;
        $param["re_openid"]=$this->re_openid;
        $param["remark"]=$this->remark;
        $param["send_name"]=$this->send_name;
        $param["total_amount"]=$this->total_amount;
        $param["total_num"]=$this->total_num;
        $param["wishing"]=$this->wishing;
        $param["wxappid"]=$this->wxappid;

        ksort($param); //按照键名排序...艹，上面排了我好久

        //$sign_raw = http_build_query($param)."&key=".$this->apikey;
        $sign_raw = "";
        foreach($param as $k => $v){
            $sign_raw .= $k."=".$v."&";
        }
        $sign_raw .= "key=".$this->apikey;

        $this->sign = strtoupper(md5($sign_raw));
    }

    /**
     * WXHongBao::genXMLParam()
     * 生成post的参数xml数据包
     * 注意生成之前各项值要生成，尤其是Sign
     * @return $xml
     */
    public function genXMLParam(){
        $xml = "<xml>
            <sign>".$this->sign."</sign>
            <mch_billno>".$this->mch_billno."</mch_billno>
            <mch_id>".$this->mch_id."</mch_id>
            <wxappid>".$this->wxappid."</wxappid>
            <nick_name><![CDATA[".$this->nick_name."]]></nick_name>
            <send_name><![CDATA[".$this->send_name."]]></send_name>
            <re_openid>".$this->re_openid."</re_openid>
            <total_amount>".$this->total_amount."</total_amount>
            <min_value>".$this->min_value."</min_value>
            <max_value>".$this->max_value."</max_value>
            <total_num>".$this->total_num."</total_num>
            <wishing><![CDATA[".$this->wishing."]]></wishing>
            <client_ip><![CDATA[".$this->client_ip."]]></client_ip>
            <act_name><![CDATA[".$this->act_name."]]></act_name>
            <remark><![CDATA[".$this->remark."]]></remark>
            <nonce_str>".$this->nonce_str."</nonce_str>
</xml>";

        return $xml;
    }

    /**
     * WXHongBao::gen_mch_billno()
     *  商户订单号（每个订单号必须唯一）
    组成： mch_id+yyyymmdd+10位一天内不能重复的数字。
    接口根据商户订单号支持重入， 如出现超时可再调用。
     * @return void
     */
    private function gen_mch_billno(){
        //生成一个长度10，的阿拉伯数字随机字符串
        $rnd_num = array('0','1','2','3','4','5','6','7','8','9');
        $rndstr = "";
        while(strlen($rndstr)<10){
            $rndstr .= $rnd_num[array_rand($rnd_num)];
        }

        $this->mch_billno = $this->mch_id.date("Ymd").$rndstr;
    }
}

?>